import router from './router'
import { ElMessage } from 'element-plus'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { getToken } from '@/utils/auth'
import { isRelogin } from '@/utils/request'
import useUserStore from '@/store/modules/user'
import usePermissionStore from '@/store/modules/permission'

NProgress.configure({ showSpinner: false })

// 免登录白名单
const whiteList = ['/user/login', '/user/register', '/admin/login']

router.beforeEach(async (to, from, next) => {
  NProgress.start()
  const hasToken = getToken()
  const userStore = useUserStore()
  const permissionStore = usePermissionStore()

  // 判断是否是管理后台路由
  const isAdminRoute = to.path.startsWith('/admin')

  if (hasToken) {
    if (to.path === '/user/login' || to.path === '/admin/login') {
      // 如果已登录，根据路由类型跳转到对应首页
      next({ path: isAdminRoute ? '/admin/index' : '/user/home' })
      NProgress.done()
    } else {
      if (userStore.roles.length === 0) {
        try {
          // 获取用户信息
          const { roles } = await userStore.getInfo()
          
          // 根据角色和路由类型生成可访问的路由
          const accessRoutes = await permissionStore.generateRoutes(roles, isAdminRoute)
          
          // 动态添加可访问路由
          accessRoutes.forEach(route => {
            router.addRoute(route)
          })

          // 确保动态路由已添加完成
          next({ ...to, replace: true })
        } catch (error) {
          // 移除 token 并跳转登录页
          await userStore.LogOut()
          ElMessage.error(error.message || '出现错误，请重新登录')
          next(isAdminRoute ? '/admin/login' : '/user/login')
          NProgress.done()
        }
      } else {
        next()
      }
    }
  } else {
    // 未登录
    if (whiteList.indexOf(to.path) !== -1) {
      // 在免登录白名单中，直接进入
      next()
    } else {
      // 根据路由类型跳转到对应登录页
      next(isAdminRoute ? '/admin/login' : '/user/login')
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  NProgress.done()
})

